package cn.tpshion.vm.service.impl;

import cn.tpshion.vm.base.config.NodeConfig;
import cn.tpshion.vm.common.utils.AESUtil;
import cn.tpshion.vm.common.utils.AssertUtil;
import cn.tpshion.vm.common.utils.DateUtil;
import cn.tpshion.vm.domain.dto.secret.AddSecretDTO;
import cn.tpshion.vm.domain.entity.Secret;
import cn.tpshion.vm.domain.entity.table.SecretTableDef;
import cn.tpshion.vm.domain.vo.SecretVO;
import cn.tpshion.vm.mapper.SecretMapper;
import cn.tpshion.vm.service.SecretService;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SecretServiceImpl implements SecretService {

    @Resource
    private SecretMapper secretMapper;

    @Resource
    private NodeConfig nodeConfig;

    @Override
    public void addSecret(AddSecretDTO dto) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(SecretTableDef.SECRET.TYPE.eq(dto.getType())
                        .and(SecretTableDef.SECRET.NAME.eq(dto.getName())));
        Secret secret = secretMapper.selectOneByQuery(queryWrapper);
        AssertUtil.isNotEmpty(secret, "密钥配置已存在，请勿重复添加");

        Secret addSecret = new Secret();
        BeanUtils.copyProperties(dto, addSecret);
        addSecret.setCreateTime(DateUtil.now());
        addSecret.setSecretKey(AESUtil.encrypt(dto.getSecretKey(), nodeConfig.getSecret()));
        addSecret.setSecretValue(AESUtil.encrypt(dto.getSecretValue(), nodeConfig.getSecret()));
        secretMapper.insertSelective(addSecret);
    }

    @Override
    public void deleteSecret(String type, String name) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(SecretTableDef.SECRET.TYPE.eq(type).and(SecretTableDef.SECRET.NAME.eq(name)));
        secretMapper.deleteByQuery(queryWrapper);
    }

    @Override
    public List<SecretVO> getSecretList(String type) {
        QueryWrapper queryWrapper = QueryWrapper.create().orderBy(SecretTableDef.SECRET.ID.asc());
        if(StringUtils.isNotBlank(type)){
            queryWrapper.where(SecretTableDef.SECRET.TYPE.eq(type));
        }
        List<Secret> list = secretMapper.selectListByQuery(queryWrapper);
        List<SecretVO> resultList = Optional.ofNullable(list).map(i -> i.stream().map(item -> {
            SecretVO result = new SecretVO();
            result.setName(item.getName());
            result.setType(item.getType());
            return result;
        })).orElseGet(null).collect(Collectors.toList());
        return resultList;
    }
}
